package com.li.utils;

import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: Li
 * Date: 2017/4/17
 * Description:
 */

public class InputFilterUtil {

    /**
     * 过滤空格
     */
    public static class NoSpaceFilter implements InputFilter{
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            return source.toString().replaceAll(" ","");
        }
    }

    /**
     * 过滤Emoji字符
     */
    public static class NoEmojiFilter implements InputFilter{
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(source);
            if (matcher.find()) {
                return "";
            }
            return null;
        }
    }

    /**
     * 保留几位小数 适用于inputType为NumberDecimal的EditText
     */
    public static class PointsFilter implements InputFilter{
        private int mPointsNum;

        private EditText mEditText;
        public PointsFilter(int pointsNum, EditText editText) {
            mPointsNum = pointsNum;
            mEditText=editText;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String txt=mEditText.getText().toString();
            if (txt.contains(".")) {
                int pointsNum=txt.substring(txt.indexOf(".")).length()-1;
                if (pointsNum==mPointsNum) {
                    return "";
                }
            }
            return null;
        }
    }
}